transition_states()Goal: We want to create an animated figure which shows the Petal.Length and Petal.Width by Species using the iris data set.
We need to use the transition_states() function. transition_states() works with discrete data.
The first step to create an animated figure is to creat the static ggplot image. This will contain “all” the data to be plotted and will not look the same as the animated figure.
We’ll load the required libraries and data set.
set.seed(923741)
library("tidyverse")
library("gganimate")
data(iris) # load the iris data
The first step is to create a static plot that contains the data that you want to present in your animated figure. Keep in mind that this plot may not look identical to the final animated figure becuase it will contain all of the data (without any transitions).
I like to build my plots step-by-step, so I save them as objects once I get them looking as I want.
iris_plot <- iris %>%
ggplot(aes(x = Petal.Width, y= Petal.Length)) +
geom_point(size = 5, alpha = 0.75, show.legend = FALSE) +
labs(x = "Petal width", y = "Petal length")
iris_plot
Static plot of the Iris data set
Eventually we will want to distinguish Species by color, but doing that now will make the animation choppy so I’ll show you that after we build the animated figure step-by-step.
With the static plot made, let’s add some animation with the transition_states() function. The user must declare the state to transition among.
iris_anim <- iris_plot +
transition_states(Species)
iris_anim
Figure with smooth animation between Iris states
transition_states() takes four arguments:
states - variable name that contains discrete datatransition_length - The relative length of the transition (default = 1)state_length - the relative length of the pause between states (default = 1)wrap - Should the animate wrap around? (default = TRUE) If TRUE the last state will be transitioned into the first.transition_states(states, transition_length, state_length, wrap = TRUE)
These transitions look a bit slow. We have considerable power to fine-tune the speed of the transitions.
iris_anim <- iris_plot +
transition_states(Species,
transition_length = 2,
state_length = 1)
iris_anim
2 second transition between states, 1 second pause at each state